<template>
  <div class="project-form">
    <el-card>
      <!-- // 面包屑导航 -->
      <div>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>
            <a href="/project">项目管理</a>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <br />
      <!-- // 筛选条件 -->
      <el-form
        ref="searchForm"
        :inline="true"
        :model="form"
        size="small"
        label-width="80px"
      >
        <el-form-item class="form-name" prop="name" label="项目名称">
          <el-input
            v-model="form.name"
            placeholder="请输入项目名称"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item class="is_delete" prop="is_delete" label="项目状态">
          <el-select v-model="form.is_delete" placeholder="请选择状态">
            <el-option
              v-for="item in items"
              :key="item.text"
              :label="item.text"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button class="search" type="primary" @click="handleSearch">
            查询
          </el-button>
          <el-button class="reset" @click="handleReset">重置</el-button>
          <el-button type="success" @click="clickAdd">新增</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        class="table"
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
        size="medium"
      >
        <el-table-column label="ID" type="index" width="50"> </el-table-column>
        <el-table-column prop="project_name" label="项目名称" width="220">
        </el-table-column>
        <el-table-column prop="desc" label="描述" width="260">
        </el-table-column>
        <!-- // 状态显示 -->

        <el-table-column prop="leader" label="权限用户">
          <template slot-scope="scope">
            <el-tag
              v-for="item in scope.row.leader"
              :key="item.username"
              type="primary"
              effect="plain"
              style="margin-left:5px"
              size="medium"
            >
              {{ item.username }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="is_delete" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.is_delete == false ? 'success' : 'danger'"
              >{{ scope.row.is_delete == false ? "正常" : "禁用" }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column label="更新人" width="100" prop="updator">
          <template slot-scope="scope">
            <el-tag type="primary" effect="plain" size="medium">
              {{ scope.row.updator }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="update_time"
          :formatter="dateFormat"
          label="更新时间"
          width="200"
        >
        </el-table-column>

        <!-- 操作按钮 -->
        <el-table-column label="操作" width="320" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click.native.prevent="clickEdit(scope.row)"
              type="primary"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <br />

      <!-- // 分页展示 -->
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        :page-sizes="[12, 20, 50, 100]"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        :disabled="loading"
        :current-page.sync="pagination.page"
        @current-change="loadProjects(pagination.page)"
      >
      </el-pagination>
    </el-card>

    <!-- 新增表单弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      :modal-append-to-body="false"
      width="600px"
      :before-close="initDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="addProjectForm"
        ref="addProjectForm"
        :rules="addProjectFormRules"
        label-width="100px"
      >
        <el-form-item prop="project_name" label="项目名称">
          <el-input v-model="addProjectForm.project_name" autocomplete="off">
          </el-input>
        </el-form-item>
        <el-form-item prop="desc" label="项目描述">
          <el-input v-model="addProjectForm.desc" autocomplete="off">
          </el-input>
        </el-form-item>

        <el-form-item prop="leader" label="权限用户">
          <el-select
            style="width:460px"
            v-model="addProjectForm.leader"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.username"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="medium"
          >取 消</el-button
        >
        <el-button type="primary" @click="submitForm" size="medium"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryProject,
  addProject,
  deleteProject,
  updateProject
} from "@/api/project";
import { getUserInfo } from "@/api/user";
import moment from "moment";

export default {
  name: "",
  props: {},
  components: {},
  data() {
    return {
      form: {
        name: undefined,
        is_delete: undefined
      },
      title: "",
      tableData: [],

      userOptions: [],

      items: [
        { type: "", text: "全部", value: undefined },
        { type: "success", text: "正常", value: 1 },
        { type: "danger", text: "禁用", value: 0 }
      ],
      loading: true,

      // 【分页属性】
      pagination: {
        total: 0,
        page: 1,
        pageSize: 12
      },

      // 弹窗控制
      dialogFormVisible: false,

      // 新增表单属性
      addProjectForm: {
        project_name: undefined,
        desc: undefined,
        leader: []
      },

      // 表单属性验证
      addProjectFormRules: {
        project_name: [
          {
            required: true,
            message: "请输入项目名称",
            max: 12,
            trigger: blur
          }
        ],
        desc: [
          {
            required: true,
            max: 50,
            min: 2,
            message: "长度在 2 到 50 个字符",
            trigger: blur
          }
        ],
        leader: [
          {
            required: true,
            trigger: blur
          }
        ]
      },

      isadd: ""
    };
  },
  computed: {},
  watch: {},
  created() {
    // 加载项目方法，进入项目就调用此方法
    this.loadProjects();
    this.loadUsers();
  },
  mounted() {},
  methods: {
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.loadProjects();
    },

    loadProjects(page = 1) {
      this.loading = true;
      queryProject({
        page,
        page_size: this.pagination.pageSize
      }).then(res => {
        this.tableData = res.data.result;
        this.pagination.total = res.data.total;
        // 关闭加载提示
        this.loading = false;
      });
    },

    // 加载所有用户
    loadUsers() {
      this.loading = true;
      getUserInfo({ page_size: 50 }).then(res => {
        this.userOptions = res.data.result;
        // 关闭加载
        this.loading = false;
      });
    },

    // 关闭弹窗
    initDialog() {
      this.$refs["addProjectForm"].resetFields();
      this.dialogFormVisible = false;
    },

    // 查询方法
    handleSearch() {
      this.loading = true;
      queryProject({
        project_name: this.form.name,
        page_size: this.pageSize,
        is_delete: this.form.is_delete
      }).then(res => {
        this.tableData = res.data.result;
        this.total = res.data.total;
        // 关闭加载提示
        this.loading = false;
      });
    },

    // 重置Form表单
    handleReset() {
      this.$refs["searchForm"].resetFields();
      this.loadProjects();
    },

    // 新增项目
    handleAdd() {
      addProject(this.addProjectForm)
        .then(res => {
          if (res.data.code === 200) {
            this.successMsg("新增成功");
          } else {
            this.$message.error(res.data.msg);
          }
          this.loadProjects(this.pagination.page);
        })
        .catch(err => {
          this.$message.error("新增失败" + err);
        });
    },

    // 编辑项目
    handleEdit() {
      updateProject(this.addProjectForm)
        .then(res => {
          if (res.data.code === 200) {
            this.successMsg("编辑成功");
          } else {
            this.$message.error(res.data.msg);
          }
          this.loadProjects(this.pagination.page);
        })
        .catch(err => {
          this.$message.error("编辑失败" + err);
        });
    },

    // 修改数据
    clickEdit(row) {
      this.title = "编辑项目";
      this.isadd = false;
      this.dialogFormVisible = true;
      this.addProjectForm.project_name = row.project_name;
      this.addProjectForm.desc = row.desc;
      this.addProjectForm.id = row.id;
      this.addProjectForm.leader = [];
      for (let j = 0; j < row.leader.length; j++) {
        this.addProjectForm.leader.push(row.leader[j].id);
      }
    },

    // 添加项目操作
    clickAdd() {
      this.title = "新增项目";
      this.isadd = true;
      this.dialogFormVisible = true;
      this.addProjectForm.project_name = undefined;
      this.addProjectForm.desc = undefined;
      this.addProjectForm.leader = undefined;
      this.addProjectForm.id = undefined;
    },

    // 新增表单确定按钮点击事件
    submitForm() {
      // 校验提交表单
      this.$refs["addProjectForm"].validate(valid => {
        // 如果表单验证失败，停止请求提交
        if (!valid) {
          return;
        }
        if (!this.isadd) {
          this.handleEdit();
        } else {
          this.handleAdd();
        }
        this.dialogFormVisible = false;
      });
    },

    // 删除操作
    handleDelete(id) {
      this.$confirm("此操作将永久删除该项目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteProject({ id }).then(res => {
            this.successMsg("删除成功");
            // 删除成功后，更新当前页的数据列表
            this.loadProjects();
          });
        })
        .catch(err => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 编写日期格式化方法
    dateFormat(row, column) {
      const date = row[column.property];
      if (date === undefined) {
        return "";
      }
      // 这里的格式根据需求修改
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },

    successMsg(msg) {
      this.$message({
        type: "success",
        message: msg
      });
    }
  }
};
</script>

<style lang="less"></style>
